﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows;

namespace sys_Print.Converter
{
    public class FontSizeAdjustmentConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values.Length < 3 || values[0] == null || values[1] == null || values[2] == null)
            {
                return DependencyProperty.UnsetValue;
            }

            string text = values[0].ToString();
            double actualWidth = (double)values[1];
            double fontSize = (double)values[2];    // 设置默认字体大小

            if (string.IsNullOrEmpty(text) || actualWidth <= 0 )
            {
                return DependencyProperty.UnsetValue;
            }

            double maxWidth = actualWidth * 0.95; // 设置最大宽度，留一些空间以防止溢出

            FormattedText formattedText = new FormattedText(
                text,
                CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                new Typeface("微软雅黑"),
                fontSize,
                Brushes.Black,
                new NumberSubstitution(),
                TextFormattingMode.Display);

            while (formattedText.Width > maxWidth && fontSize > 1)
            {
                fontSize -= 1; // 递减字体大小，直到宽度适合为止
                formattedText.SetFontSize(fontSize);
            }

            return fontSize;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
}
